package com.eerl.pdev.util;

import com.eerl.pdev.MySettingsState;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import org.jetbrains.annotations.NotNull;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class EToolPluginConsoleToolWindowFactory implements ToolWindowFactory {

    private static final String DEBUG_TAG = "[DEBUG] ";

    // xll_todo 配置化
    private static final int TOO_BIG_STRING_LEN = 3000;

    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        ConsoleView consoleView = TextConsoleBuilderFactory.getInstance().createBuilder(project).getConsole();
        Content content = ContentFactory.getInstance().createContent(consoleView.getComponent(), "", false);
        toolWindow.getContentManager().addContent(content);

        // 将 ConsoleView 存储在项目级别
        project.putUserData(ConsoleViewKey.KEY, consoleView);
    }


    private static void print0(Project project, String message, ConsoleViewContentType type, boolean includeModeAndLine) {
        ConsoleView consoleView = project.getUserData(ConsoleViewKey.KEY);

        if (consoleView != null) {
            String formattedDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if (MySettingsState.getInstance().Is_DEBUG) {
                // 获取调用栈信息
                StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
                String callerInfo = "Unknown";
                if (stackTrace.length > 3) {
                    StackTraceElement caller = stackTrace[3]; // 索引3是因为0是getStackTrace，1是当前方法
                    callerInfo = caller.getClassName() + ":" + caller.getLineNumber();
                }

                String fullMessage = String.format("[%s] [%s] %s\n", formattedDate, callerInfo, message);
                consoleView.print(fullMessage, type);
            } else {
                String fullMessage = String.format("[%s] %s\n", formattedDate, message);
                consoleView.print(fullMessage, type);
            }
        }
    }

    public static void printToConsole(Project project, String message) {
        print0(project, message, ConsoleViewContentType.NORMAL_OUTPUT, true);
    }

    public static void printSimpleToConsole(Project project, String message) {
        if (!MySettingsState.getInstance().Is_DEBUG && message.length() >= TOO_BIG_STRING_LEN) {
            message = message.substring(0, TOO_BIG_STRING_LEN - 1) + "...(Too Big, Cut!Or Open Debug Mod)";
        }
        print0(project, message, ConsoleViewContentType.NORMAL_OUTPUT, false);
    }

    public static void errSimpleToConsole(Project project, String message) {
        print0(project, message, ConsoleViewContentType.ERROR_OUTPUT, false);
    }

    public static void errToConsole(Project project, String message) {
        print0(project, message, ConsoleViewContentType.ERROR_OUTPUT, true);
    }

    public static void debugPrint(Project project, String s) {
        if (MySettingsState.getInstance().Is_DEBUG) {
            print0(project, DEBUG_TAG + s, ConsoleViewContentType.SYSTEM_OUTPUT, true);
        }
    }
}

// 定义一个 Key 来存储 ConsoleView
class ConsoleViewKey {
    static final Key<ConsoleView> KEY = Key.create("EToolPluginConsoleView");
}